layui.use(['table', 'form', 'jquery', 'laydate', 'layer'], function () {
    let table = layui.table;
    let layer = layui.layer;
    let form = layui.form;
    let laydate = layui.laydate;
    let $ = layui.$;

    let BIZ_NAME = 'consumption-records';
    let BIZ_TABLE = 'consumption-records-table';
    let BIZ_FORM = 'consumption-records-form';
    let FIT_BIZ_FORM = 'fit-consumption-records-form';
    let BIZ_QUERY = 'consumption-records-query';
    let tableConsumptionRecordsObj;
    let formConsumptionRecordsObj;
    let formFitConsumptionRecordsObj;

    //消費列表加載
    window.renderConsumptionRecordsTable = function (where) {
        let cols = [
            [
                {title: '记录编号', field: 'id', align: 'center', width: 100},
                // {title: '会员ID', field: 'memberId', align: 'center'},
                {title: '消费充值金额', field: 'amount', align: 'center'},
                {title: '消费赠送金额', field: 'giftAmount', align: 'center'},
                {title: '消费项目', field: 'items', align: 'center'},
                {title: '消费时间', field: 'consumptionTime', align: 'center'},
                {title: '操作人', field: 'operators', align: 'center'}
            ]
        ]

        tableConsumptionRecordsObj = table.render({
            elem: '#' + BIZ_TABLE,
            url: '/' + BIZ_NAME + '/page',
            where: where,
            text: {none: '暂无相关数据'},
            response: {
                statusCode: 200,
                msgName: 'message'
            },
            page: true,
            limit: 10,
            limits: [10, 20, 50],
            cols: cols,
            skin: 'line',
            defaultToolbar: [{
                layEvent: 'refresh',
                icon: 'layui-icon-refresh',
            }, 'filter', 'print', 'exports']
        });

        table.on('toolbar(' + BIZ_TABLE + ')', function (obj) {
            if (obj.event === 'add') {
                window.consumptionRecordsForm();
            } else if (obj.event === 'refresh') {
                window.refreshConsumptionRecords();
            }
        });
    }

    //新增会员消费记录
    window.consumptionRecordsForm = function (obj) {
        let title = '会员消费/计次';
        //初始化$('#rechargeId')下拉框内容
        $("#rechargeId").empty();
        form.render("select");
        //初始化服务项目内容
        $('#fitItems').val('');
        $('#items').val('');

        formConsumptionRecordsObj = layer.open({
            type: 1,
            title: title,
            shade: 0.1,
            area: ['60%', '85%'],
            btn: ['立即提交', '取消'],
            yes: function (index, layero) {
                $('#' + BIZ_FORM + ' [lay-submit]').click();
            },
            cancel: function (index, layero) {
                layer.close(index);
            },
            content: $('#' + BIZ_FORM),
            success: function (layero, index) {
                //隐藏计次消费的输入框
                $('#timesDiv').hide();
                $('#moneyDiv').show();
                if (obj) {
                    //重置表单，清空上次输入的值
                    document.getElementById(BIZ_FORM).reset();
                    // 填充会员信息数据
                    $('#consumptionMemberId').val(obj.id);
                    $('#consumptionMemberName').val(obj.name);
                    $('#consumptionOperators').val(obj.createdBy);

                    //动态加载服务项目
                    dynamicCheckBox("/item/list", "#item_checkbox");

                    // 如果是会员计次消费，则查询会员充次记录
                    if (obj.id && obj.id !== undefined && obj.id !== null) {
                        $.ajax({
                            url: '/recharge-times/list?memberId=' + obj.id + '&remainingTimesGreaterThan=0',
                            type: 'GET',
                            success: function (res) {
                                if (res.code === 200) {
                                    let data = res.data; // 获取返回的数据
                                    $.each(data, function (i, item) {
                                        $('#rechargeId').append('<option value="' + item.id + '">' + item.activityName + '（' + item.remainingTimes + '次）' + '</option>'); // 将数据添加到下拉框中
                                    });
                                    form.render('select');
                                } else {
                                    layer.alert(res.message, {icon: 2}); // 显示错误信息
                                }
                            }
                        });
                    }
                } else {
                    layer.alert('请选择会员后再进行新增!', {icon: 2});
                }
            },
            id: 'consumption-records-form-id'
        });
    }

    // 会员消费表单提交
    form.on('submit(' + BIZ_FORM + ')', function (data) {
        let url = '/save';
        let type = 'POST';
        //如果id不为空则调用修改接口
        if (data.field.id) {
            url = '/update'
            type = 'POST';
        }

        //这里要判断提交类型，
        // 如果是金额消费，调用consumption-records/save接口，
        // 如果是计次消费，调用consumption-times/save接口
        let choseVale = $("input[name='type']:checked").val();
        if (choseVale && choseVale === '金额消费') {
            $.ajax({
                url: '/' + BIZ_NAME + url,
                data: JSON.stringify(data.field),
                type: type,
                dataType: 'json',
                contentType: 'application/json',
                success: function (result) {
                    if (result.code === 200) {
                        layer.msg(result.message, {icon: 1, time: 1000}, function () {
                            layer.close(formConsumptionRecordsObj);
                            //执行重载
                            table.reload('member-table', {
                                page: {
                                    curr: 1 //重新从第 1 页开始
                                }
                                , where: {}
                            });
                        });
                    } else {
                        layer.alert(result.message, {icon: 2});
                    }
                }
            })
        } else {//计次消费
            $.ajax({
                url: '/consumption-times' + url,
                data: JSON.stringify(data.field),
                type: type,
                dataType: 'json',
                contentType: 'application/json',
                success: function (result) {
                    if (result.code === 200) {
                        layer.msg(result.message, {icon: 1, time: 1000}, function () {
                            layer.close(formConsumptionRecordsObj);
                            //执行重载
                            table.reload('member-table', {
                                page: {
                                    curr: 1 //重新从第 1 页开始
                                }
                                , where: {}
                            });
                        });
                    } else {
                        layer.alert(result.message, {icon: 2});
                    }
                }
            })
        }
        return false;
    });

    // 动态加载服务项目复选框
    function dynamicCheckBox(url, id) {
        $.ajax({
            url: url,
            type: 'GET',
            dataType: 'json',
            success: function (res) {
                let checkboxArr = '';
                $.each(res.data, function (index, item) {
                    let its = '<input type="checkbox" name="item[' + item.id + ']" lay-filter="items-checkbox-filter" ' +
                        'title="' + item.name + '" style="margin-top: 10px;">';
                    checkboxArr += its;
                });
                $(id).html(checkboxArr);
                form.render('checkbox');
            }
        });
    };

    //散客消费弹窗
    window.fitConsumptionRecordsForm = function (obj) {
        let title = '散客消费';
        formFitConsumptionRecordsObj = layer.open({
            type: 1,
            title: title,
            shade: 0.1,
            area: ['60%', '85%'],
            btn: ['立即提交', '取消'],
            yes: function (index, layero) {
                $('#' + FIT_BIZ_FORM + ' [lay-submit]').click();
            },
            cancel: function (index, layero) {
                layer.close(index);
            },
            content: $('#' + FIT_BIZ_FORM),
            success: function (layero, index) {
                //重置表单，清空上次输入的值
                document.getElementById(FIT_BIZ_FORM).reset();
                // 填充会员信息数据
                $('#fitConsumptionMemberId').val(0);

                //动态加载服务项目
                dynamicCheckBox("/item/list", "#fit_item_checkbox");
            },
            id: 'fit-consumption-records-form-id'
        });
    }

    // 散客消费提交
    form.on('submit(' + FIT_BIZ_FORM + ')', function (data) {
        let url = '/save';
        let type = 'POST';
        //如果id不为空则调用修改接口
        if (data.field.id) {
            url = '/update'
            type = 'POST';
        }

        $.ajax({
            url: '/' + BIZ_NAME + url,
            data: JSON.stringify(data.field),
            type: type,
            dataType: 'json',
            contentType: 'application/json',
            success: function (result) {
                if (result.code === 200) {
                    layer.msg(result.message, {icon: 1, time: 1000}, function () {
                        layer.close(formFitConsumptionRecordsObj);
                        //执行重载
                        table.reload('member-table', {
                            page: {
                                curr: 1 //重新从第 1 页开始
                            }
                            , where: {}
                        });
                    });
                } else {
                    layer.alert(result.message, {icon: 2});
                }
            }
        })
        return false;
    });

    // 项目复选框选择事件
    form.on('checkbox(items-checkbox-filter)', function (data) {
        var elem = data.elem; // 获得 checkbox 原始 DOM 对象
        var checked = elem.checked; // 获得 checkbox 选中状态
        var value = elem.title; // 获得 checkbox 值

        //处理服务项目字段
        let items = $('#fitItems').val();
        if (checked) {
            if (items.length > 0) {
                items += ',' + value;
            } else {
                items = value;
            }
        } else {
            if (items.indexOf(value) > -1) {
                items = items.replace(value, '');
            }
        }
        items = items.replace(',,', ',');
        //items的首个字符如果是, 则去掉
        if (items.charAt(0) === ',') {
            items = items.substr(1);
        }
        $('#fitItems').val(items);
        $('#items').val(items);
    });

    // 单选框 radio 选择事件
    form.on('radio(consumptionType)', function (data) {
        let selectedValue = data.value; // 获取选中的值

        if (selectedValue && selectedValue === '金额消费') {
            //隐藏计次消费的输入框
            $('#timesDiv').hide();
            $('#moneyDiv').show();
        } else {
            //隐藏金额消费的输入框
            $('#moneyDiv').hide();
            $('#timesDiv').show();

        }
    });
});